package com.qipay.sms.service.impl;

import com.qipay.configuration.config.ConfigurationEnum;
import com.qipay.configuration.service.ConfigurationService;
import com.qipay.sms.config.AliyunSMSTemplateEnum;
import com.qipay.sms.service.SmsService;
import com.qipay.sms.utils.ALiyunSMSOldUtils;
import com.qipay.sms.utils.CodeCacheUtils;
import com.qipay.sms.utils.MonyunUtils;
import io.jsonwebtoken.lang.Assert;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 * Creator: Yao
 * Date:    2017/10/18
 * For:
 * Other:
 */
@Service
public class SmsServiceImpl implements SmsService {

    final static Logger logger = LogManager.getLogger(SmsServiceImpl.class);

    @Autowired
    ALiyunSMSOldUtils ALliyunSMSUtils;
    @Autowired
    ConfigurationService configurationService;
    @Autowired
    CodeCacheUtils codeCacheUtils;


    @Override
    @Async
    public void withdrawInform(String code) {

        // check
        if (StringUtils.isBlank(code)) {
            logger.error("提现申请通知时，未提供业务编码");
            return;
        }

        // init
        String phones = configurationService.select(ConfigurationEnum.WITHDRAW_INFORM_STAFF.getType());
        if (StringUtils.isBlank(phones)) {
            logger.error("提现申请通知时，未找到指定接收人员信息");
            return;
        }
        String[] staffs = phones.split(",");
        for (String p : staffs) {
            logger.info(String.format("通知[%s]: %s", p, String.format(AliyunSMSTemplateEnum.BUSINESS.getInfoTemplate(), code)));
            ALliyunSMSUtils.send(p, AliyunSMSTemplateEnum.BUSINESS.getCode(), String.format(AliyunSMSTemplateEnum.BUSINESS.getTemplate(), code));
        }
    }

    @Override
    public String valid(String phone) {

        // check
        Assert.isTrue(StringUtils.isNotBlank(phone), "未提供接收短信校验码的手机");

        // init
//        String validCode = codeCacheUtils.generateValidCode(phone, AliyunSMSTemplateEnum.VALID.getCode());
//        logger.info(String.format("通知[%s]: %s", phone, String.format(AliyunSMSTemplateEnum.VALID.getInfoTemplate(), validCode)));
//        ALliyunSMSUtils.send(phone, AliyunSMSTemplateEnum.VALID.getCode(), String.format(AliyunSMSTemplateEnum.VALID.getTemplate(), validCode));
        String validCode = codeCacheUtils.generateValidCode(phone, AliyunSMSTemplateEnum.MONYUNVALID.getCode());
        logger.info(String.format("通知[%s]: %s", phone, String.format(AliyunSMSTemplateEnum.MONYUNVALID.getInfoTemplate(), validCode)));
        MonyunUtils.send(phone,String.format(AliyunSMSTemplateEnum.MONYUNVALID.getInfoTemplate(), validCode));

        return validCode;
    }
}
